package com.mobileClientKernel.android.commonLayer;

import android.content.Context;
import android.os.Environment;

import java.io.File;

public class CacheManager {
    public static File rootDir = new File(Environment.getExternalStorageDirectory(), "jj");

    /**
     * 获取缓存目录 SDCard/jj/xx
     *
     * @param context
     * @param fileName 文件名
     * @return
     */
    public static File getCacheFile(Context context, String fileName) {

        File appCacheDir = null;
        if ("mounted".equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) {
            appCacheDir = new File(rootDir, fileName);
        }

        if (appCacheDir == null || !appCacheDir.exists() && !appCacheDir.mkdirs()) {
            appCacheDir = context.getCacheDir();
        }

        return appCacheDir;
    }

    /**
     * 判断应用是否有SDCard写入权限
     *
     * @param context
     * @return
     */
    public static boolean hasExternalStoragePermission(Context context) {
        int perm = context.checkCallingOrSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE");
        return perm == 0;
    }

    public static long getDirSize(File rootDir) {
        if (rootDir == null) {
            return 0;
        }
        if (!rootDir.isDirectory()) {
            return 0;
        }
        long dirSize = 0;
        File[] files = rootDir.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                dirSize += file.length();
            } else if (file.isDirectory()) {
                dirSize += file.length();
                dirSize += getDirSize(file); // 递归调用继续统计
            }
        }
        return dirSize;


    }

    public static boolean clearCache(final File rootDir) {
        new Thread() {
            @Override
            public void run() {
                try {
                    if (rootDir != null) {
                        if (rootDir.isFile() || rootDir.list() == null) {
                            rootDir.delete();
                        } else {
                            if (rootDir.listFiles() != null) {
                                File[] files = rootDir.listFiles();
                                for (File f : files) {
                                    clearCache(f);//递归删除每一个文件
                                    f.delete();//删除该文件夹
                                }
                            }
                        }
                    }
                }catch (Exception e){
                    JJLog.e("[clearCache] Exception!");
                }
            }
        }.start();
        return true;
    }
}
